#ifndef LOGMANAGEMENT_H
#define LOGMANAGEMENT_H

#include <QWidget>
#include <QStandardItemModel>
#include <QSqlDatabase>
#include <QDateTime>
#include <QTimer>
#include <QStyledItemDelegate>
#include <QSqlError>
#include "databasemanager.h"
#include "usermanager.h"

namespace Ui {
class LogManagement;
}

class LogLevelDelegate : public QStyledItemDelegate
{
    Q_OBJECT
public:
    explicit LogLevelDelegate(QObject *parent = nullptr);
    void paint(QPainter *painter, const QStyleOptionViewItem &option,
               const QModelIndex &index) const override;
};

class LogManagement : public QWidget
{
    Q_OBJECT

public:
    enum LogType {
        SYSTEM_LOG = 0,
        OPERATION_LOG,
        ALARM_LOG,
        EXCEPTION_LOG
    };

    enum LogLevel {
        LOG_INFO = 0,
        LOG_WARNING,
        LOG_ERROR,
        LOG_CRITICAL
    };

    explicit LogManagement(QWidget *parent = nullptr);
    ~LogManagement();

    static void log(const QString &content,
                  LogType type = SYSTEM_LOG,
                  LogLevel level = LOG_INFO,
                  int userId = -1,
                  int deviceId = -1);

    void setUserManager(UserManager* userManager);
    static void setEncryptionEnabledStatic(bool enabled) { s_encryptionEnabled = enabled; }

private slots:
    void onQueryButtonClicked();
    void onExportButtonClicked();
    void onDeleteButtonClicked();
    void onClearButtonClicked();
    void showContextMenu(const QPoint &pos);
    void refreshLogs();
    void onSearchTextChanged(const QString &text);
    void onEncryptActionTriggered();
    void onAuditActionTriggered();
    void performLogRotation();

private:
    void initUI();
    void initConnections();
    void loadLogs();
    bool checkUserPermission();
    void encryptLogContent(QString &content);
    void decryptLogContent(QString &content);
    void setupLogRotationTimer();
    void exportToFile(const QString &fileName, const QString &format);

    Ui::LogManagement *ui;
    QStandardItemModel *m_logsModel;
    LogLevelDelegate *m_logLevelDelegate;
    UserManager *m_userManager;
    QTimer *m_refreshTimer;
    QTimer *m_rotationTimer;
    bool m_encryptionEnabled;
    int m_maxLogSizeMB;
    int m_keepLogDays;
    static bool s_encryptionEnabled;
};

#endif // LOGMANAGEMENT_H
